//
//  WNTypeBookVC.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/11.
//

import UIKit

class WNTypeBookVC: WNBaseVC {
    
    lazy var typeColView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.itemSize = CGSize(width: ScreenW, height: scaleWidth(116)+12)
        let col = UICollectionView.init(frame: .zero, collectionViewLayout: layout)
        col.showsVerticalScrollIndicator = false
        col.showsHorizontalScrollIndicator = false
        col.backgroundColor = .init(named: "white_F7F7F7")
        col.delegate = self
        col.dataSource = self
        col.register(TypeColCell.self, forCellWithReuseIdentifier: TypeColCell.identifier)
        col.ly_emptyView = WNEmptyView.wn_loadStyle(descStr: .common, imageStr: .common, tapBlock: { [weak self] in
            col.mj_header?.beginRefreshing()
        })
        col.isHidden = true
        return col
    }()
    
    var tagModel: TagsModel?

    var isTag = true
            
    var bookArr = [BookDetailModel]()
        
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewConfig() {
        view.addSubview(typeColView)
        typeColView.snp.makeConstraints { make in
            make.top.equalTo(NaviTotalHeight)
            make.left.right.equalTo(0)
            make.bottom.equalTo(-TabBarMargin)
        }
    }
    
    override func dataConfig() {
        pageName = "Tag or Category"
        navView.titleName = tagModel?.label_name
        listSettingRefresh()
        bookListRequest()
    }
}

extension WNTypeBookVC {

    func listSettingRefresh() {
        typeColView.mj_header = wn_refreshHeader(completion: { [weak self] in
            self?.page = 1
            self?.hasPage = false
            self?.bookListRequest()
        })
        
        typeColView.mj_footer = wn_refreshFooter(completion: { [weak self] in
            if self?.page == 1 && (self?.bookArr.count ?? 0) == 0 {
                self?.typeColView.mj_footer?.endRefreshing()
                return
            }
            if self?.hasPage == true {
                self?.page += 1
                self?.bookListRequest()
            }else {
                self?.typeColView.mj_footer?.endRefreshingWithNoMoreData()
            }
        })
    }
}

extension WNTypeBookVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        bookArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: TypeColCell.identifier, for: indexPath) as! TypeColCell
        cell.model = bookArr[indexPath.item]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        wn_pushBookVC(bookArr[indexPath.item].bookId ?? "")
    }
}

extension WNTypeBookVC {
    
    func bookListRequest() {
        provider_discover.rx.request(isTag ? .tag(tagModel?.id ?? "", page) : (tagModel?.id ?? "" == "GUESS YOU LIKE" ? .guesslike(page) : .categocry(tagModel?.id ?? "", page)))
            .asObservable().mapModel(BaseModel<[BookDetailModel]>.self)
            .subscribe(onNext: { [weak self] (model) in
                self?.typeColView.isHidden = false
                self?.typeColView.ly_emptyView.imageStr = EmptyImage.common.rawValue
                self?.typeColView.ly_emptyView.detailStr = EmptyDesc.common.rawValue
                self?.typeColView.ly_emptyView.btnTitleStr = ""
                guard model.code == 0 else {
                    if (self?.isFirst ?? true) {
                        self?.typeColView.ly_emptyView.imageStr = EmptyImage.serverBad.rawValue
                        self?.typeColView.ly_emptyView.detailStr = EmptyDesc.serverBad.rawValue
                        self?.typeColView.ly_emptyView.btnTitleStr = "Click Refresh"
                    }else {
                        self?.wn_toast(model.msg ?? "")
                    }
                    self?.typeColView.mj_header?.endRefreshing()
                    self?.typeColView.mj_footer?.endRefreshing()
                    self?.isFirst = false
                    return
                }
                if self?.page == 1 {
                    self?.bookArr.removeAll()
                    self?.typeColView.mj_footer?.resetNoMoreData()
                }
                if let arr = model.data {
                    self?.hasPage = arr.count > 9
                    self?.bookArr += arr
                }else {
                    self?.typeColView.mj_footer?.endRefreshingWithNoMoreData()
                }
                self?.typeColView.reloadData()
                self?.typeColView.mj_header?.endRefreshing()
                self?.typeColView.mj_footer?.endRefreshing()
                self?.isFirst = false
            }, onError: { [weak self] (error) in
                self?.wn_toast("Check the network connection")
                self?.typeColView.ly_emptyView.imageStr = EmptyImage.netWork.rawValue
                self?.typeColView.ly_emptyView.detailStr = EmptyDesc.netWork.rawValue
                self?.typeColView.ly_emptyView.btnTitleStr = "Click Refresh"
                self?.typeColView.mj_header?.endRefreshing()
                self?.typeColView.mj_footer?.endRefreshing()
                self?.typeColView.isHidden = false
            }).disposed(by: rx.disposeBag)
    }
}
